import 'react-native-url-polyfill/auto'
import { UserInfoType } from '../types/user'
import React, { useRef, useEffect, useState, useContext } from 'react'

import {
  View,
  Text,
  TouchableOpacity,
  Card,
  Colors,
  Image,
  Modal
} from 'react-native-ui-lib'
import { ImageBackground, ScrollView, Dimensions } from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons'
import { AppStyles, AppColors, TextStyles } from '../theme/uiLib.config'
import { useRouter } from 'expo-router'
import mockMerchants from '../data/mockMerchants'
import { ModalContext } from './_layout'

import { myFetch } from '../utils/fetchRequest'
import '../utils/mock'

const index = () => {
  const router = useRouter()
  const scrollViewRef = useRef(null)
  const [currentIndex, setCurrentIndex] = useState(0)
  const { hasShownModal, setHasShownModal } = useContext(ModalContext)
  const [userInfo,setUserInfo] = useState<UserInfoType>({
    id:'',
    sex:'男',
    userName:'',
    familyJiFen:0,
    familyMemberNum:0,
    bandAccountNum:0
  }) 
  // const [count,setCount] = useState(0)
  // useEffect(() => {
  //   console.log('effect count',count)
  //   setCount(count + 1)
  // }, [count]);

  // useEffect(() => {
  //   console.log('effect []')
  // }, []);
  // 模拟接口请求

  const backgroundImages = [
    require('../../assets/images/ad1.jpg'),
    require('../../assets/images/ad2.jpg'),
    require('../../assets/images/ad3.jpg')
  ]
  // let scrollIntervalTimeHandler = null

  // 处理滚动结束事件
  const handleScroll = (event) => {
    // console.log('handleScroll event')
    const contentOffset = event.nativeEvent.contentOffset.x
    const index = Math.round(contentOffset / Dimensions.get('window').width)
    // console.log('handleScroll index:',index)
    setCurrentIndex(index)
    // console.log('scrollIntervalTimeHandler:',scrollIntervalTimeHandler)
    // clearInterval(scrollIntervalTimeHandler)
  }

  useEffect(() => {
    const scrollIntervalTimeHandler = setInterval(() => {
      setCurrentIndex((prevIndex) => {
        // console.log('prevIndex:',prevIndex)
        const nextIndex = (prevIndex + 1) % backgroundImages.length
        scrollViewRef.current?.scrollTo({
          x: nextIndex * Dimensions.get('window').width,
          animated: true
        })
        // console.log('nextIndex:',nextIndex)
        return nextIndex
      })
    }, 5000)

    return () => clearInterval(scrollIntervalTimeHandler)
  }, [])

  // 轮播指示器
  const renderDots = () => {
    return (
      <View
        style={{
          position: 'absolute',
          bottom: 64,
          flexDirection: 'row',
          alignSelf: 'center'
        }}
      >
        {backgroundImages.map((_, index) => (
          <View
            key={index}
            style={{
              width: 8,
              height: 8,
              borderRadius: 4,
              backgroundColor:
                currentIndex === index ? AppColors.golden : '#ffffff',
              marginHorizontal: 4,
              opacity: currentIndex === index ? 1 : 0.5
            }}
          />
        ))}
      </View>
    )
  }

  const closeModal = () => {
    setHasShownModal(true)
  }

  useEffect(()=>{
    const getUserInfo = async () => {
      console.log('getUserInfo event')
      // let data0 = await request('/getUserInfo')
      // console.log('getUserInfo data0:',data0)
      let data = await myFetch('/api/getUserInfo', {
        method: 'GET'
      }) as UserInfoType
      console.log('setUserInfo:',data)
      setUserInfo(data)
      
    }
    getUserInfo()
  },[])
  
  

  return (
    <ScrollView>
      {/* 弹窗 */}
      <Modal
        visible={!hasShownModal}
        transparent={true}
        animationType='fade'
        onRequestClose={closeModal}
      >
        <View
          style={{
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: 'rgba(0,0,0,0.7)'
          }}
        >
          <TouchableOpacity
            style={{
              alignSelf: 'flex-end',
              marginBottom: 10,
              marginRight: 20
            }}
            onPress={closeModal}
          >
            <Icon name='close-circle-outline' size={24} color={Colors.grey20} />
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => {
              closeModal()
              router.push('/BindAccount')
            }}
            activeOpacity={1}
          >
            <ImageBackground
              source={require('../../assets/images/bg/3.png')}
              style={{
                width: Dimensions.get('window').width * 0.9,
                aspectRatio: 1 / 1, // 保持宽高比
                borderRadius: 12,
                alignItems: 'flex-end',
                padding: 10,
                position: 'relative',
                overflow: 'hidden'
              }}
              resizeMode='cover'
            ></ImageBackground>
          </TouchableOpacity>
        </View>
      </Modal>

      {/* 上半屏  */}
      <View style={{ height: 480, backgroundColor: 'transparent'}}>
        <View style={{ position: 'relative' }}>
          <ScrollView
            ref={scrollViewRef}
            horizontal
            pagingEnabled
            showsHorizontalScrollIndicator={false}
            scrollEnabled={true}
            onMomentumScrollEnd={handleScroll}
          >
            {backgroundImages.map((image, index) => (
              <ImageBackground
                key={index}
                source={image}
                style={{
                  height: 320,
                  width: Dimensions.get('window').width
                }}
                resizeMode='cover'
              />
            ))}
          </ScrollView>

          {/* 轮播指示器 */}
          {renderDots()}

          {/* 固定在顶部的 logo 和积分账户栏目 */}
          <View style={{ position: 'absolute', top: 0, left: 0, right: 0 }}>
            {/* logo */}
            <View
              style={{
                alignItems: 'flex-start',
                justifyContent: 'flex-start',
                marginTop: 50,
                marginLeft: 16
              }}
            >
              <Image
                source={require('../../assets/images/logo.png')}
                style={{
                  width: 100,
                  height: 20,
                  backgroundColor: 'transparent'
                }}
                resizeMode='contain'
              />
            </View>

            {/* 积分帐户栏目 */}
            <Card
              style={[
                AppStyles.cardStyle,
                {
                  marginTop: 200,
                  backgroundColor: '#ffffff',
                  marginLeft: 12,
                  marginRight: 12
                }
              ]}
            >
              {/* 积分帐户标题 */}
              <View
                style={{
                  height: 50,
                  backgroundColor: AppColors.blueplus,
                  flexDirection: 'row',
                  alignItems: 'center',
                  borderTopLeftRadius: 8,
                  borderTopRightRadius: 8,
                  shadowColor: '#fff', // 内发光效果色
                  shadowOffset: { width: 0, height: 0 }, // 光效偏移
                  shadowOpacity: 0.3, // 光效透明度
                  shadowRadius: 1 // 光效模糊半径
                }}
              >
                <TouchableOpacity>
                  <Image
                    source={require('../../assets/images/avater.png')}
                    style={{
                      width: 32,
                      height: 32,
                      borderRadius: 16,
                      marginLeft: 16,
                      marginRight: 10
                    }}
                  />
                </TouchableOpacity>

                {userInfo && <Text style={[TextStyles.smaller, { color: Colors.golden }]}>
                  Hey,{userInfo.userName}，今天来集分吧！
                </Text>}
                <TouchableOpacity
                  style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    marginLeft: 'auto',
                    backgroundColor: 'transparent',
                    paddingVertical: 14,
                    paddingHorizontal: 18
                  }}
                  onPress={() => {
                    router.push('/BindAccount')
                  }}
                >
                  <Text style={[TextStyles.small, { color: Colors.golden }]}>
                    绑定商户 +{' '}
                  </Text>
                </TouchableOpacity>
              </View>

              <TouchableOpacity
                onPress={() => {
                  router.push('/MyFamilyPoints')
                }}
              >
                {/* 积分账户信息 */}
                <View
                  style={{
                    flexDirection: 'row',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    height: 160 // 固定高度确保居中
                  }}
                >
                  {/* 左侧区域 */}
                  {userInfo && <View
                    style={{
                      flex: 1,
                      alignItems: 'center',
                      justifyContent: 'center',
                      height: '100%'
                    }}
                  >
                    <Image
                      source={require('../../assets/images/member.png')}
                      style={{ width: 48, height: 48 }}
                    />
                    <Text style={[TextStyles.primaryBold, { marginTop: 8 }]}>
                      家庭成员
                    </Text>
                    <Text
                      style={[
                        TextStyles.number,
                        { color: Colors.secondary, marginTop: 8 }
                      ]}
                    >
                      {' ' + userInfo.familyMemberNum + ' '}
                    </Text>
                  </View>
                  }

                  {/* 中间区域 */}
                  {userInfo && <View
                    style={{
                      flex: 1,
                      alignItems: 'center',
                      justifyContent: 'center',
                      height: '100%'
                    }}
                  >
                    <Image
                      source={require('../../assets/images/passbook.png')}
                      style={{ width: 48, height: 48 }}
                    />
                    <Text style={[TextStyles.primaryBold, { marginTop: 8 }]}>
                      绑定商户
                    </Text>
                    <Text
                      style={[
                        TextStyles.number,
                        { color: Colors.secondary, marginTop: 8 }
                      ]}
                    >
                      {' ' + userInfo.bandAccountNum + ' '} 
                    </Text>
                  </View>
                  }

                  {/* 右侧区域 */}
                  <View
                    style={{
                      flex: 1,
                      alignItems: 'center',
                      justifyContent: 'center',
                      height: '100%'
                    }}
                  >
                    <Image
                      source={require('../../assets/images/coin.png')}
                      style={{ width: 48, height: 48 }}
                    />
                    <Text style={[TextStyles.primaryBold, { marginTop: 8 }]}>
                      全家积分
                    </Text>
                    <Text
                      style={[
                        TextStyles.number,
                        { color: Colors.secondary, marginTop: 8 }
                      ]}
                    >
                      {' ' + userInfo && userInfo.familyJiFen || 0 + ' '} 
                    </Text>
                  </View>
                </View>
              </TouchableOpacity>
            </Card>
          </View>
        </View>
      </View>

      {/* 下半屏  */}
      <View flex style={[AppStyles.pagePadding, { marginTop: 10 }]}>
        {/* 我家保单  */}
        <Card style={AppStyles.cardStyle}>
          <View
            style={{
              height: 60,
              backgroundColor: '#FFE5CF',
              flexDirection: 'row',
              alignItems: 'center',
              borderTopLeftRadius: 8,
              borderTopRightRadius: 8
            }}
          >
            {/*  <Image
              source={require('../../assets/images/family.png')}
              style={{ width: 32, height: 32, marginLeft: 16, marginRight: 12 }}
            /> */}
            <Text
              style={[
                TextStyles.h3,
                { marginLeft: 16, color: Colors.tertiary }
              ]}
            >
              全家保障
            </Text>
            <TouchableOpacity
              style={{
                borderRadius: 20,
                flexDirection: 'row',
                alignItems: 'center',
                marginLeft: 'auto',
                marginRight: 20,
                backgroundColor: Colors.primary,
                paddingVertical: 10,
                paddingHorizontal: 14
              }}
              onPress={() => {
                router.push('/Insure/AddInsurance')
              }}
            >
              <Text style={[TextStyles.small, { color: Colors.white }]}>
                领取保障
              </Text>
              <Icon name='chevron-forward' size={14} color={Colors.white} />
            </TouchableOpacity>
          </View>

          <TouchableOpacity
            onPress={() => {
              router.push('/Insure/InsureranceList')
            }}
          >
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'flex-start',
                height: 80 // 固定高度确保居中
              }}
            >
              <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <Text
                  style={[
                    TextStyles.number,
                    { color: Colors.primary, marginLeft: 20, marginRight: 3 }
                  ]}
                >
                  2
                </Text>
                <Text
                  style={[
                    TextStyles.small,
                    { color: Colors.tertiary, marginRight: 30 }
                  ]}
                >
                  人保障中
                </Text>
              </View>

              <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <Text
                  style={[
                    TextStyles.number,
                    { color: Colors.primary, marginLeft: 20, marginRight: 3 }
                  ]}
                >
                  2
                </Text>
                <Text
                  style={[
                    TextStyles.small,
                    { color: Colors.tertiary, marginRight: 40 }
                  ]}
                >
                  份保单
                </Text>
              </View>
              <Text
                style={[
                  TextStyles.small,
                  { marginLeft: 'auto', marginRight: 40, color: Colors.primary }
                ]}
              >
                立即查看
              </Text>
            </View>
          </TouchableOpacity>
        </Card>

        <View style={{ flexDirection: 'row', flexWrap: 'wrap' }}>
          <Text
            style={[TextStyles.h3, { color: Colors.tertiary, marginTop: 22 }]}
          >
            热门积分商户
          </Text>
          <View
            style={{
              flexDirection: 'row',
              flexWrap: 'wrap',
              justifyContent: 'space-between',
              marginTop: 10
            }}
          >
            {/* 手动渲染商户列表 */}
            {mockMerchants.map((merchant) => (
              <MerchantItem key={merchant.id} merchant={merchant} />
            ))}
          </View>
        </View>
      </View>
    </ScrollView>
  )
}

// 提取商户信息组件
const MerchantItem: React.FC<{ merchant: Merchant }> = ({ merchant }) => {
  const router = useRouter()

  return (
    <TouchableOpacity
      style={AppStyles.merchantItem}
      onPress={() => router.push(`/MerchantDetail?id=${merchant.id}`)}
    >
      <Image
        source={merchant.image}
        style={AppStyles.merchantImage}
        resizeMode='cover'
      />
      <Text style={[TextStyles.primaryBold, AppStyles.merchantName]}>
        {merchant.name}
      </Text>
      <Text style={[TextStyles.small, AppStyles.merchantRatio]}>
        兑换比例: {merchant.ratio}
      </Text>
      <View style={{ flexDirection: 'row', alignItems: 'baseline' }}>
        <Icon
          name='location-sharp'
          size={12}
          color={Colors.secondary}
          marginLeft={12}
        />
        <Text style={[TextStyles.smaller, AppStyles.merchantLocation]}>
          {merchant.location}
        </Text>
      </View>
    </TouchableOpacity>
  )
}

export default index
